from PIL import Image


def gen_png(path, size=(50, 50), color=(0, 0, 0, 0)) -> str:
    """
    根据颜色生成图片
    :param path:
    :param size: (50, 50)
    :param color: (255, 255, 255, 255) 或 #FFFFFFFF 或 #FFFFFF
    :return:
    """
    mode = 'RGBA'
    # 格式化color
    rgba = color
    if isinstance(color, str):
        color = color.lstrip('#')
        if len(color) == 6:  # RGB
            r = int(color[0:2], 16)
            g = int(color[2:4], 16)
            b = int(color[4:6], 16)
            a = 255  # 默认为不透明
        elif len(color) == 8:  # RGBA
            r = int(color[0:2], 16)
            g = int(color[2:4], 16)
            b = int(color[4:6], 16)
            a = int(color[6:8], 16)
        else:
            print('param invalid, use #rrggbb or #rrggbbaa')
        rgba = (r, g, b, a)

    # 创建一个新的 RGBA 图像
    image = Image.new(mode, size, rgba)
    # 保存图片到本地文件
    image.save(path)
    return path


if __name__ == '__main__':
    # print(gen_png('resources/11.png', color='#00ffff'))
    print(gen_png('resources/img/button_comm.png', size=(2, 2), color='#2f4751b2'))  # #2f4751b2 (47, 71, 81, 178) (0.529, 0.808, 0.922, 0.7)
    print(gen_png('resources/img/button_comm_pressed.png', size=(2, 2), color='#1a84beb2'))  # #2f4751b2 (26, 132, 190, 178)
    print(gen_png('resources/img/button_comm_form.png', size=(2, 2), color='#1a84be20'))  # #1a84be20
    print(gen_png('resources/img/button_comm_option.png', size=(2, 2), color=(230, 51, 102, 128)))  #  #e633667f  (230, 51, 102, 128)  (0.9, 0.2, 0.4, 0.5)

    # print(gen_png('resources/22.png', color='#00ffff', size=(200, 200)))
    # print(gen_png('resources/33.png', color=(88, 88, 88, 178), size=(200, 200)))
    # print(gen_png('resources/33.png', color=(222, 88, 88, 178), size=(200, 200)))
    # print(gen_png('resources/33.png', color=(int(0.529*255), int(0.808*255), int(0.922*255), int(0.7*255)), size=(200, 200)))
    # print(gen_png('resources/33.png', color=(135, 206, 235, 178), size=(200, 200)))
